<template>
  <div>
    <van-nav-bar
      title="个人信息"
      fixed
      placeholder
      z-index="999"
      left-arrow
      @click-left="$router.back()"
    />

 
      <van-cell title="头像" center>
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <!-- 上传的功能    -->
          <!--  input定位定到img上   透明度0 -->
          <input
            id="file"
            @change="uploadImg"
            type="file"
            style="display: none"
          />

          <label for="file">
            <van-image round width="60" height="60" :src="userInfo.avatar" />
          </label>
        </template>
      </van-cell>

      <van-field
        v-model="userInfo.nickname"
        label="昵称"
        placeholder="请填写昵称"
        input-align="right"
      />
      <van-field
        :value="userInfo.username"
        label="用户名"
        placeholder="用户名"
        input-align="right"
        readonly
      />

      <van-field name="radio" label="性别" input-align="right">
        <template #input>
          <van-radio-group v-model="userInfo.gender" direction="horizontal">
            <van-radio name="男">男</van-radio>
            <van-radio name="女">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-model="userInfo.addr"
        type="text"
        label="地址"
        placeholder="请选择地址"
        input-align="right"
        readonly
        @click="cityPickerShow = true"
      />
      <div style="margin: 16px">
        <van-button round block type="info" color="#DB281F"  @click="onSubmit"
          >提交</van-button
        >
      </div>
  

    <!--   弹出层  -->

    <van-popup v-model="cityPickerShow" position="bottom">
      <!--  这里边放三级联动数据    -->

      <van-area
        :area-list="areaList"
        @confirm="cityPickerConfirm"
        @cancel="cityPickerShow = false"
        :value="userInfo.addrCode"
      />
    </van-popup>
  </div>
</template>

<script>
import { Form, Field, RadioGroup, Radio, Area, Popup } from "vant";
import { areaList } from "@vant/area-data";
export default {
  name: "userInfo",
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Popup.name]: Popup,
    [Area.name]: Area,
  },
  data() {
    return {
      cityPickerShow: false,
      // area 需要完整的JSON
      areaList,
      userInfo: {},
    };
  },
  created() {
    //  A   稍微不那么严谨   节省  
    // let userInfo = localStorage.getItem("xl-userInfo");
    // if (userInfo) {
    //   this.userInfo = JSON.parse(userInfo);
    // }
    // A的另一种写法
// 还有一种方案  从 $root获取


   //  B  更严谨  但是浪费  
    this.getUserInfo();
  },
  methods: {
    getUserInfo() {
      let token = localStorage.getItem("xl-token"); //
      if (!token) {
        setTimeout((v) => {
          this.$router.back();
        }, 800);
        this.$toast("参数错误");
        return;
      }
      this.$http
        .post("/user/kh/getMyUserInfo", {
          uni_id_token: token,
        })
        .then((res) => {
          if (res.code == 0) {
            this.userInfo = res.userInfo;
          } else {
            this.$toast(res.msg);
          }

          //  console.log(res)
        });
    },
    onSubmit(e) {
      let { addr, addrCode, nickname, avatar, gender } = this.userInfo;

      let uni_id_token = localStorage.getItem('xl-token');

      this.$http.post('/user/kh/updateUser',{
        addr, addrCode, nickname, avatar, gender,uni_id_token
      })
      .then(res=>{
           console.log(res)
           if(res.code == 0){
             this.$toast('修改成功')
             
             let {userInfo} = res;

             localStorage.setItem('xl-userInfo',JSON.stringify(userInfo));
             this.$root.userInfo = userInfo;

             setTimeout(v=>{
               this.$router.back()
             },800)


           }else{
             this.$toast('修改失败')
           }
      })

     
    },
    //  确定 城市联动选择
    cityPickerConfirm(data) {
      console.log(data);
      this.cityPickerShow = false;
      this.userInfo.addr = data.map((v) => v.name).join("-");
      this.userInfo.addrCode = data.reverse()[0].code;
    },
    //  上传头像
    async uploadImg(e) {
      let file = e.target.files[0];

      console.log(file);

      //   1. 需要获取到一个上传前的凭证

      let { token } = await this.getUploadToken();

      console.log(token);

      let exname = file.name.slice(file.name.lastIndexOf("."));

      let key = `${new Date().getTime()}_${Math.random()
        .toString(36)
        .slice(2)}${exname}`;

      //  2.  三个参数一起发给七牛云的服务器  token   file  文件名

      // 想上传文件  FormData

      let formData = new FormData();

      formData.append("key", key);
      formData.append("token", token);
      formData.append("file", file);

      this.$http.post("https://upload-z1.qiniup.com", formData).then((res) => {
        console.log(res);

        let avatar = `http://toutiao.longxiaokj.com/${res.key}`;

        this.userInfo.avatar = avatar;
        //  给对象动态的添加属性 并不会触发自动更新
        this.$forceUpdate();
      });
    },

    //  获取上传前的凭证
    getUploadToken() {
      return this.$http.get(
        "https://d33a5037-6c63-4e92-8bb1-30018ab701ea.bspapp.com/http/upload/token"
      );
    },
  },
};
</script>

<style>
</style>